package co.fitstart.weapp.api.web.controller.course;

import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;

import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.StudentTargetData;
import co.fitstart.entity.user.User;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.StudentTargetService;
import co.fitstart.weapp.api.service.UserService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/profile/courses/{courseId}/target")
public class StudentTargetController {

    private static final Logger logger = LoggerFactory.getLogger(StudentTargetController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private StudentTargetService studentTargetService;

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult load(@RequestParam("unionid") String unionid,
                           @PathVariable("courseId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            StudentTargetData studentTargetData =studentTargetService.load(courseRound);
            
            if(studentTargetData == null) {
                httpResult.success().message("获取数据成功");
            } else {
                httpResult.success().message("获取数据成功")
                                    .data("targetData", studentTargetData);
            }
            
            Date effectiveStart = courseRound.getEffectiveStart() != null ? courseRound.getEffectiveStart() : new Date();
            Date effectiveEnd = courseRound.getEffectiveEnd() != null ? courseRound.getEffectiveEnd() : courseRound.calculateEffectiveEnd(effectiveStart);
            
            httpResult.data("startYear", DateFormatUtils.format(effectiveStart, "yyyy"))
                      .data("startDate", DateFormatUtils.format(effectiveStart, "MM月dd日"))
                      .data("endYear", DateFormatUtils.format(effectiveEnd, "yyyy"))
                      .data("endDate", DateFormatUtils.format(effectiveEnd, "MM月dd日"));
            
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("load() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 确认不录入课程目标
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/full-in-target/cancel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult cancelFullInTarget(@RequestParam("unionid") String unionid,
                                         @PathVariable("courseId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            studentTargetService.cancelFullInTarget(courseRound);
            
            httpResult.success().message("确认不录入目标成功");
        } catch (Exception e) {
            logger.error("create() error", e);
            httpResult.fail("500").message("确认不录入目标失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult create(@RequestParam("unionid") String unionid,
                             @PathVariable("courseId") Long courseRoundId,
                             @RequestBody StudentTargetData studentTargetData) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            studentTargetService.create(courseRound, studentTargetData);
            
            httpResult.success().message("保存目标成功")
                                .data("give", courseRound.getCourse().isGive())
                                .data("siteId", courseRound.getSite().getId())
                                .data("coachId", courseRound.getCoach().getId());
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("create() error", e);
            httpResult.fail("500").message("保存目标失败");
        }
        
        return httpResult;
    }
}
